<template>
  <div class="user-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="角色" style="width: 180px">
          <el-select v-model="searchForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"/>
            <el-option label="普通用户" value="user"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-area">
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="70"/>
        <el-table-column prop="avatarUrl" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatarUrl"/>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="address" label="家庭地址" width="180"/>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : ''">
              {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单 -->
    <el-dialog title="用户详情" v-model="disabled" :width="400">
      <el-form label-width="80px" :model="userForm">
        <div style="width: 300px; height: 300px; margin-bottom: 20px;margin-left: 40px">
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarChange"
          >
            <img
                style="width: 100%;
                 height: 100%;
                 object-fit: cover;"
                v-if="userForm.avatarUrl"
                :src="userForm.avatarUrl"
                alt=""/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input type="textarea" v-model="userForm.address" placeholder="请输入家庭住址"/>
        </el-form-item>
        <el-form-item label="角色" style="width: 180px" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"/>
            <el-option label="普通用户" value="USER"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="disabled = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {reqDeleteUser, reqGetUserList, reqSaveUserInfo} from "@/apis/user";
import {Plus} from "@element-plus/icons-vue";
import {ElMessage, UploadProps} from "element-plus";
import {generateMD5OfFile} from "@/utils/md5.ts";
import {reqImage} from "@/apis/image";

const searchForm = ref({
  username: '',
  role: ''
})

const userForm = ref({
  username: '',
  password: '',
  email: '',
  phone: '',
  address: '',
  role: '',
  avatarUrl: '',
  imageId: ''
})

const disabled = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])


const getUserList = async (pager = 1) => {
  page.value = pager
  const result: any = await reqGetUserList({
    page: page.value,
    size: pageSize.value,
    name: searchForm.value.username,
    role: searchForm.value.role
  })
  if (result.code === 200) {
    userList.value = result.data.records
    total.value = result.data.total
  }
}

// 搜索
const handleSearch = () => {
  getUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    role: ''
  }
  getUserList()
}

// 新增用户
const handleAdd = () => {
  Object.assign(userForm.value, {
    username: '',
    email: '',
    phone: '',
    address: '',
    role: '',
    avatarUrl: '',
    imageId: ''
  })
  disabled.value = true
}
// 获取用户的详细信息
// const handleDetail = async (id: number) => {
//   const result: any = await reqUserInfoById(id)
//   if (result.code === 200) {
//     userForm.value = result.data
//   }
// }
// 编辑用户
const handleEdit = (row: any) => {
  Object.assign(userForm.value, row)
  disabled.value = true
}

// 保存用户
const handleSave = async () => {
  const result: any = await reqSaveUserInfo(userForm.value)
  if (result.code === 200) {
    ElMessage.success('保存成功')
    disabled.value = false
    await getUserList()
  } else {
    ElMessage.error(result.message)
  }
}

// 删除用户
const handleDelete = async (row: any) => {
  const result = await reqDeleteUser(row.id)
  if (result.code === 200) {
    ElMessage.success('删除成功')
    await getUserList()
  } else {
    ElMessage.error('删除失败')
  }
}

// 分页相关
const handleSizeChange = () => {
  getUserList()
}

const handleCurrentChange = () => {
  getUserList()
}
// 图像上传
const handleAvatarChange = async (data: any) => {

  try {
    const md5 = await generateMD5OfFile(data.file)
    const formData = new FormData();
    // 添加文件到formData对象中
    formData.append('file', data.file);
    formData.append('md5', md5);
    const result: any = await reqImage(formData)
    if (result.code === 200) {
      userForm.value.avatarUrl = result.data.filePath
      userForm.value.imageId = result.data.id
      ElMessage.success('上传成功')
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('Error:', error)
  }

}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    uploadFile
) => {
  userForm.value.avatarUrl = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }

  return true
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped lang="scss">
.user-container {
  .operation-area {
    margin: 15px 0;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.avatar-uploader {
  width: 100%;
  position: relative;
  height: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c9399;
  width: 100%;
  height: 100%;
  position: absolute;  /* 新增定位 */
}

</style> 